package isanfeng.tuxiaoer.rabbitmq.comfirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建一个ConnectionFactory，并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.56.101");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 2. 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 3. 通过connection创建一个Channel
        Channel channel = connection.createChannel();

        // 4. 制定我们的消息投递模式：消息的确认模式
        channel.confirmSelect();
        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.save";

        String msg = "hello rabbit mq!";
        // 5. 发送一条消息
        System.out.println("生产端：" + msg);
        channel.basicPublish(exchangeName, routingKey, null, (msg).getBytes());
        // 6. 添加一个确认监听
        channel.addConfirmListener(new ConfirmListener() {
            /**
             *
             * @param deliveryTag 消息唯一的标签
             * @param multiple
             * @throws IOException
             */
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("--- ack---");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("--- no ack---");
            }
        });
    }
}
